import { defineStore } from "pinia";
import {ref} from 'vue'
import { post } from "@/utils/request";

export const useLoginStore = defineStore('login', () => {
  const token = ref(localStorage.getItem('token'))
  const userRole = ref(localStorage.getItem('userRole'))

  // 存储token和userId
  const setToken = (newtoken,userId,role) => {
    token.value = newtoken
    localStorage.setItem('token',newtoken)
    localStorage.setItem('userId',userId)
    localStorage.setItem('userRole', role)
  }

  const loginRequest = async (loginForm) => {
    try{
      const response = await post('/login',{
        userId:loginForm.userId,
        password:loginForm.password
      })
      console.log(response)
      setToken(response.data.token,loginForm.userId, response.data.role)
      return response.data.role
    }catch(error){
      console.error(error)
    }
  }

  return {loginRequest,userRole}
})